package com.bw.finance.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {
    public static List<Map> readExcel(String ext,InputStream inputStream) throws Exception {
        List<Map> list=new ArrayList<Map>();
        Workbook wb=null;
        if(".xls".equals(ext)){
            wb=new HSSFWorkbook(inputStream);
        }
        if(".xlsx".equals(ext)){
            wb=new XSSFWorkbook(inputStream);
        }
        Sheet sheet = wb.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        for (int i=2;i<=rowNum;i++){
            Row row = sheet.getRow(i);
            Map map=new HashMap();

            short cellNum = row.getLastCellNum();
            for(int j=0;j<cellNum;j++){
                String key = getDataKey(sheet.getRow(1).getCell(j));
                Object value = getDataValue(row.getCell(j));
                map.put(key,value);
            }
            list.add(map);
        }
        return list;
    }

    public static String getDataKey(Cell cell){
        return cell.getStringCellValue();
    }

    public static Object getDataValue(Cell cell){
        if(null==cell){
            return null;
        }
        int cellType = cell.getCellType();
        Object value=null;
        switch (cellType){
            case Cell.CELL_TYPE_STRING:
                value=cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value=null;
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value=cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if(DateUtil.isCellDateFormatted(cell)){
                    value=cell.getDateCellValue();
                }else{
                    value=cell.getNumericCellValue();
                }
                break;
        }
        return value;
    }
}
